import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/home/index.vue')
      },
      {
        path: 'books',
        name: 'Books',
        component: () => import('@/views/books/index.vue')
      },
      {
        path: 'book/:id',
        name: 'BookDetail',
        component: () => import('@/views/books/detail.vue')
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/user/profile.vue')
      },
      {
        path: 'borrow',
        name: 'Borrow',
        component: () => import('@/views/borrow/index.vue')
      },
      {
        path: 'collection',
        name: 'Collection',
        component: () => import('@/views/collection/index.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/register/index.vue')
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('@/layout/admin.vue'),
    redirect: '/admin/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/admin/dashboard.vue')
      },
      {
        path: 'book-manage',
        name: 'BookManage',
        component: () => import('@/views/admin/book-manage.vue')
      },
      {
        path: 'category-manage',
        name: 'CategoryManage',
        component: () => import('@/views/admin/category-manage.vue')
      },
      {
        path: 'borrow-manage',
        name: 'BorrowManage',
        component: () => import('@/views/admin/borrow-manage.vue')
      },
      {
        path: 'user-manage',
        name: 'UserManage',
        component: () => import('@/views/admin/user-manage.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else if (!token) {
    next('/login')
  } else {
    next()
  }
})

export default router